import sys
import threading

# Global objects
# In core process they are referencing real core objects
# In service they are referencing rpc clients

# NOTE: for Service objects self.<> is more prefferable than salsa.<>
core = None
logger = None
service = None

# global flag to synchronize salsa stopping
stopping = False

# Tracing
import traceback

trace_exceptions = True

# Writes all log strings to stderr
trace_log = False

trace_io_obj = False
trace_io = False
trace_rpc = False

# enable tracing threading module
trace_threads = False

# Print stack on sigint/sigterm
trace_interrupt = False

# trace_exec_flow traces start(), stop() and _run() functions
trace_exec_flow = False

# 
trace_tree_proc = True

threading._VERBOSE = trace_threads

def do_trace(msg):
    print >> sys.stderr, msg

def do_trace_exception(where):
    if trace_exceptions:
        print >> sys.stderr, 'Exception occured: %s' % where
        print >> sys.stderr, traceback.format_exc()

def do_trace_interrupt():
    if trace_interrupt:
        try:
            import faulthandler
            
            faulthandler.dump_traceback()
        except ImportError:
            pass

# SALSAException

class SALSAException(Exception):
    def __init__(self, *args):
        if len(args) > 0 and trace_exceptions:
            do_trace(args[0])
        
        Exception.__init__(self, args)